package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.StoreServiceType;
import com.probox.common.core.enums.StoreServiceTypeEnum;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.GaoDeUtil;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.platfom.PlatformStore;
import com.probox.common.entity.domain.platfom.PlatformStoreGroup;
import com.probox.common.entity.mapper.platfom.PlatformStoreGroupMapper;
import com.probox.common.entity.mapper.platfom.PlatformStoreMapper;
import com.probox.common.entity.mapper.system.SysUserMapper;
import com.probox.common.entity.service.platfom.IPlatformStoreService;
import com.probox.common.redis.service.RedisService;
import com.probox.platform.api.domain.PlatformStoreVo;
import com.probox.systemApi.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 门店信息Service业务层处理
 *
 * @author usoft
 * @date 2021-08-20
 */
@Service
@Transactional
public class PlatformStoreServiceImpl extends ServiceImpl<PlatformStoreMapper, PlatformStore> implements IPlatformStoreService {
    @Autowired
    private PlatformStoreMapper platformStoreMapper;

    @Autowired
    private PlatformStoreGroupMapper platformStoreGroupMapper;


    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RedisService redisService;

    private final String sImg = "?imageslim";



    @Override
    public List<PlatformStore> getStoreByServiceType(List<String>  serviceType, Long storeId) {
        QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        if (storeId != null) {
            queryWrapper.eq("store_uid", storeId);
        }else{
            queryWrapper.in("service_Type", serviceType);
        }
        return platformStoreMapper.selectList(queryWrapper);
    }

    /**
     * 查询门店信息
     *
     * @param storeUid 门店信息ID
     * @return 门店信息
     */
    @Override
    public PlatformStore selectPlatformStoreById(Long storeUid) {
        return this.getById(storeUid);
    }

    /**
     * 查询门店信息列表
     *
     * @param platformStore 门店信息
     * @return 门店信息
     */
    @Override
    public List<PlatformStore> queryList(PlatformStore platformStore) {
        QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreUid())) && platformStore.getStoreUid() != null) {
            queryWrapper.eq("STORE_UID", platformStore.getStoreUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getAppid())) && platformStore.getAppid() != null) {
            queryWrapper.like("APPPID", platformStore.getAppid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreName())) && platformStore.getStoreName() != null) {
            queryWrapper.like("STORE_NAME", platformStore.getStoreName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreContacts())) && platformStore.getStoreContacts() != null) {
            queryWrapper.eq("STORE_CONTACTS", platformStore.getStoreContacts());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStorePhone())) && platformStore.getStorePhone() != null) {
            queryWrapper.eq("STORE_PHONE", platformStore.getStorePhone());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreProvince())) && platformStore.getStoreProvince() != null) {
            queryWrapper.eq("STORE_PROVINCE", platformStore.getStoreProvince());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreCity())) && platformStore.getStoreCity() != null) {
            queryWrapper.eq("STORE_CITY", platformStore.getStoreCity());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreArea())) && platformStore.getStoreArea() != null) {
            queryWrapper.eq("STORE_AREA", platformStore.getStoreArea());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreAddress())) && platformStore.getStoreAddress() != null) {
            queryWrapper.eq("STORE_ADDRESS", platformStore.getStoreAddress());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreBanner())) && platformStore.getStoreBanner() != null) {
            queryWrapper.eq("STORE_BANNER", platformStore.getStoreBanner());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreImg())) && platformStore.getStoreImg() != null) {
            queryWrapper.eq("STORE_IMG", platformStore.getStoreImg());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreLongitude())) && platformStore.getStoreLongitude() != null) {
            queryWrapper.eq("STORE_LONGITUDE", platformStore.getStoreLongitude());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreLatitude())) && platformStore.getStoreLatitude() != null) {
            queryWrapper.eq("STORE_LATITUDE", platformStore.getStoreLatitude());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getDataStatus())) && platformStore.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", platformStore.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getAuditStatus())) && platformStore.getAuditStatus() != null) {
            queryWrapper.eq("AUDIT_STATUS", platformStore.getAuditStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getCreateUid())) && platformStore.getCreateUid() != null) {
            queryWrapper.eq("CREATE_UID", platformStore.getCreateUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getCreateName())) && platformStore.getCreateName() != null) {
            queryWrapper.eq("CREATE_NAME", platformStore.getCreateName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getUpdateUid())) && platformStore.getUpdateUid() != null) {
            queryWrapper.eq("UPDATE_UID", platformStore.getUpdateUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getUpdateName())) && platformStore.getUpdateName() != null) {
            queryWrapper.eq("UPDATE_NAME", platformStore.getUpdateName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getAuditUid())) && platformStore.getAuditUid() != null) {
            queryWrapper.eq("AUDIT_UID", platformStore.getAuditUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getAuditName())) && platformStore.getAuditName() != null) {
            queryWrapper.eq("AUDIT_NAME", platformStore.getAuditName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getAuditTime())) && platformStore.getAuditTime() != null) {
            queryWrapper.eq("AUDIT_TIME", platformStore.getAuditTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getCustomerUid())) && platformStore.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", platformStore.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getStoreType())) && platformStore.getStoreType() != null) {
            queryWrapper.eq("STORE_TYPE", platformStore.getStoreType());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformStore.getServiceType())) && platformStore.getServiceType() != null) {
            queryWrapper.eq("service_Type", platformStore.getServiceType());
        }

        if (CollectionUtil.isNotEmpty(platformStore.getTypes())) {
            queryWrapper.in("service_Type", platformStore.getTypes());
        }
        queryWrapper.orderByDesc("update_time");
        return platformStoreMapper.selectList(queryWrapper);
    }

    /**
     * 新增门店信息
     *
     * @param platformStore 门店信息
     * @return 结果
     */
    @Override
    public boolean insertPlatformStore(PlatformStore platformStore) {
        // 名称不能重名
        Integer result = queryName(platformStore.getStoreName(), null);
        if (result > 0) {
            throw new ProductException("门店名称不能重名！");
        }
        Long userId = SecurityUtils.getUserId();
        DateTime date = DateUtil.date();
        String username = SecurityUtils.getUsername();
        platformStore.setPlatformUid(SecurityUtils.getPlatformId());
        platformStore.setCreateUid(userId);
        platformStore.setUpdateUid(userId);
        platformStore.setCreateName(username);
        platformStore.setUpdateName(username);
        platformStore.setUpdateTime(date);
        platformStore.setCreateTime(date);
        platformStore.setAuditStatus(DataStatus.valid.getKey());
        platformStore.setDataStatus(DataStatus.valid.getKey());
        /**
         * 获取经纬度
         */
        List<String> geo = GaoDeUtil.geo(platformStore.getStoreProvince() + platformStore.getStoreCity() + platformStore.getStoreCity() +
                platformStore.getStoreAddress());
        if (CollectionUtil.isNotEmpty(geo)) {
            platformStore.setStoreLatitude(geo.get(1));
            platformStore.setStoreLongitude(geo.get(0));
        }
        boolean save = this.save(platformStore);

        return save;

    }

    /**
     * 修改门店信息
     *
     * @param platformStore 门店信息
     * @return 结果
     */
    @Override
    public boolean updatePlatformStore(PlatformStore platformStore) {
        Integer result = queryName(platformStore.getStoreName(), platformStore.getStoreUid());
        if (result > 0) {
            throw new ProductException("门店名称不能重名！");
        }
        platformStore.setUpdateUid(SecurityUtils.getUserId());
        platformStore.setUpdateName(SecurityUtils.getUsername());
        platformStore.setUpdateTime(DateUtil.date());
        /**
         * 获取经纬度
         */
        List<String> geo = GaoDeUtil.geo(platformStore.getStoreProvince() + platformStore.getStoreCity() + platformStore.getStoreCity() +
                platformStore.getStoreAddress());
        if (CollectionUtil.isNotEmpty(geo)) {
            platformStore.setStoreLatitude(geo.get(1));
            platformStore.setStoreLongitude(geo.get(0));
        }



        boolean b = this.updateById(platformStore);
        redisService.deleteObject(CachePrefix.PLATFOR_STORE_DETAIL + platformStore.getStoreUid());
        redisService.deleteObject(CachePrefix.PLATFORM_STORE_LIST + SecurityUtils.getPlatformId());

        return b;
    }

    /**
     * 批量删除门店信息
     *
     * @param storeUids 需要删除的门店信息ID
     * @return 结果
     */
    @Override
    public boolean deletePlatformStoreByIds(Long[] storeUids) {
        UpdateWrapper<PlatformStore> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("store_UID", Arrays.asList(storeUids));
        updateWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    public Integer queryName(String name, Long uid) {
        QueryWrapper<PlatformStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_NAME", name);
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (uid != null) {
            queryWrapper.ne("STORE_UID", uid);
        }
        Integer integer = platformStoreMapper.selectCount(queryWrapper);
        return integer;
    }

    /**
     * 获取门店详情
     *
     * @param store
     * @return
     */
    @Override
    public PlatformStoreVo getVo(PlatformStore store) {
        String key = CachePrefix.PLATFOR_STORE_DETAIL + store.getStoreUid();
        PlatformStoreVo vo = redisService.get(key, PlatformStoreVo.class);
        if (ObjectUtil.isEmpty(vo)) {
            vo = new PlatformStoreVo();
            QueryWrapper<PlatformStore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_uid", store.getStoreUid());
            queryWrapper.eq("platform_uid", store.getPlatformUid());
            PlatformStore platformStore = platformStoreMapper.selectOne(queryWrapper);
            if (ObjectUtil.isEmpty(platformStore)) return vo;
            BeanUtils.copyProperties(platformStore, vo);
            if (ObjectUtil.isNotEmpty(vo.getStoreBanner())) {
                // 瘦身图片
                StringBuffer stringBuffer = new StringBuffer();
                String[] split = vo.getStoreBanner().split(",");
                for (int i = 0; i < split.length; i++) {
                    if (0 > split[i].indexOf(sImg)) split[i] = split[i] + sImg;
                    stringBuffer.append("," + split[i]);
                }
                vo.setStoreBanner(stringBuffer.toString());
                vo.setStoreBanner(vo.getStoreBanner().substring(1, vo.getStoreBanner().length()));
            }
            if (ObjectUtil.isNotEmpty(vo.getStoreImg())) {
                // 瘦身图片
                StringBuffer stringBuffer = new StringBuffer();
                String[] split = vo.getStoreImg().split(",");
                for (int i = 0; i < split.length; i++) {
                    if (0 > split[i].indexOf(sImg)) split[i] = split[i] + sImg;
                    stringBuffer.append("," + split[i]);
                }
                vo.setStoreImg(stringBuffer.toString());
                vo.setStoreImg(vo.getStoreImg().substring(1, vo.getStoreImg().length()));
            }
            redisService.set(key, vo, 1L, TimeUnit.DAYS);
        }
        return vo;
    }

    /**
     * 门店下拉列表
     *
     * @param platformUid
     * @return
     */
    @Override
    public List<PlatformStoreVo> listSelect(Long platformUid) {
        return platformStoreMapper.listSelect(platformUid);
    }


    @Override
    public List<PlatformStoreVo> appletHomeList(Long platformUid) {
        String key = CachePrefix.PLATFORM_STORE_LIST + platformUid;
        List<PlatformStoreVo> cacheList = redisService.getCacheList(key);
        if (CollectionUtil.isEmpty(cacheList)) {
            cacheList = platformStoreMapper.appletHomeList(platformUid);
            if (!CollectionUtils.isEmpty(cacheList)) {
                redisService.setCacheList(key, cacheList);
                redisService.expire(key, RedisService.FIVEMINUTE, TimeUnit.SECONDS);
            }
        }
        return cacheList;
    }

    @Override
    public List<PlatformStore> listRecommend() {

        PlatformStore platformStore = new PlatformStore();
        platformStore.setTypes(new ArrayList<>());
        if (ObjectUtil.isNotEmpty(userMapper.selectUserById(SecurityUtils.getUserId()).getStoreGroupId())) {
            if (CollectionUtil.isNotEmpty(platformStoreMapper.selectLife(userMapper.selectUserById(SecurityUtils.getUserId()).getStoreGroupId())))
                platformStore.getTypes().add("probxplus");
            platformStore.getTypes().add("Medical");
            return listQuery(platformStore);
        } else {
            if (SecurityUtils.getStoreId() != null) {
                String type = platformStoreMapper.selectById(SecurityUtils.getStoreId()).getServiceType();
                if (StoreServiceTypeEnum.Life.getKey().equals(type))
                    platformStore.getTypes().add("probxplus");
            }
            platformStore.getTypes().add("Medical");
            return listQuery(platformStore);
        }

    }

    @Override
    public List<PlatformStore> selectGroup() {
        QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
        SysUser sysUser = userMapper.selectUserById(SecurityUtils.getUserId());
        if (ObjectUtil.isNotEmpty(sysUser.getStoreGroupId())) {
            PlatformStoreGroup platformStoreGroup = platformStoreGroupMapper.selectById(sysUser.getStoreGroupId());
            if (ObjectUtil.isNotEmpty(platformStoreGroup)) {
                queryWrapper.in("store_uid", platformStoreGroup.getStoreIds().split(","));
            }
        } else if (ObjectUtil.isNotEmpty(sysUser.getStoreId())) {
            queryWrapper.eq("store_uid", sysUser.getStoreId());
        }

        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        return platformStoreMapper.selectList(queryWrapper);
    }

    @Override
    public List<PlatformStore> listSelectGroup(Long platformId) {
        QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();

        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        return platformStoreMapper.selectList(queryWrapper);
    }

    @Override
    public List<PlatformStore> getStoreByServiceType(Set<String> serviceType) {
        QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("occupation_status", DataStatus.valid.getKey());
        queryWrapper.in("service_Type", serviceType);
        return platformStoreMapper.selectList(queryWrapper);
    }

    public List<PlatformStore> listQuery(PlatformStore platformStore) {
        QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.in("service_Type", platformStore.getTypes());
        return platformStoreMapper.selectList(queryWrapper);
    }

    /**
     * 门店下拉列表
     *
     * @param platformUid
     * @return
     */
    @Override
    public List<PlatformStore> listSelectSelf(Long platformUid) {

        long store = userMapper.selectUserById(SecurityUtils.getUserId()).getStoreId();


        if (ObjectUtil.isNotEmpty(userMapper.selectUserById(SecurityUtils.getUserId()).getStoreGroupId())) {
            QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
            queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
            queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
            queryWrapper.in("STORE_UID", Arrays.asList(platformStoreGroupMapper.selectById(userMapper.selectUserById(SecurityUtils.getUserId()).getStoreGroupId()).getStoreIds()));
            return platformStoreMapper.selectList(queryWrapper);
        }
        return Collections.singletonList(platformStoreMapper.selectById(store));
    }

    /**
     * 根据门店分组查询门店
     *
     * @param storeGroupId
     * @return
     */
    @Override
    public List<PlatformStore> selectByUser(Long storeGroupId) {
        /**
         *
         */

        PlatformStoreGroup platformStoreGroup = platformStoreGroupMapper.selectById(storeGroupId);
        if (ObjectUtil.isNotEmpty(platformStoreGroup)) {
            String[] split = platformStoreGroup.getStoreIds().split(",");
            QueryWrapper<PlatformStore> queryWrapper = Wrappers.query();
            queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
            queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
            queryWrapper.in("STORE_UID", Arrays.asList(split));
            return platformStoreMapper.selectList(queryWrapper);
        }
        return new ArrayList<>();
    }

    /**
     * 查询没有门店分组的门店
     *
     * @param uid
     * @return
     */
    @Override
    public List<PlatformStore> selectNoGroup(Long uid) {
        /**
        QueryWrapper<PlatformStoreGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_status", DataStatus.valid.getKey());
        if (ObjectUtil.isNotEmpty(uid)) {
            queryWrapper.ne("group_id", uid);
        }
        List<PlatformStoreGroup> platformStoreGroups = platformStoreGroupMapper.selectList(queryWrapper);
        List<String> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(platformStoreGroups)) {
            platformStoreGroups.forEach(vo -> {
                if (StringUtils.isNotEmpty(vo.getStoreIds())) {
                    String[] split = vo.getStoreIds().split(",");
                    List<String> addList = new ArrayList<>(split.length);
                    Collections.addAll(addList, split);
                    list.addAll(addList);
                }

            });
        }
         */
        QueryWrapper<PlatformStore> queryWrapperStore = Wrappers.query();
        queryWrapperStore.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapperStore.ne("DATA_STATUS", DataStatus.delete.getKey());

        //if (list.size()>0) {
            //queryWrapperStore.notIn("STORE_UID", list);
        //}
        return platformStoreMapper.selectList(queryWrapperStore);
    }


    /**
     * 根据当前人查询门店
     *
     * @return
     */
    @Override
    public List<PlatformStore> selectStoreByWork(String type) {
        SysUser user = userMapper.selectUserById(SecurityUtils.getUserId());
        QueryWrapper<PlatformStore> queryWrapperStore = Wrappers.query();
        queryWrapperStore.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapperStore.eq("DATA_STATUS", DataStatus.valid.getKey());
        List<String> typeList  = new ArrayList<>();
        typeList.add(StoreServiceType.probxplus.getKey());
        typeList.add(type);
        if (ObjectUtil.isNotEmpty(user.getStoreGroupId())) {
            QueryWrapper<PlatformStoreGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("data_status", DataStatus.valid.getKey());
            queryWrapper.eq("group_id", user.getStoreGroupId());
            List<PlatformStoreGroup> platformStoreGroups = platformStoreGroupMapper.selectList(queryWrapper);
            List<String> list = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(platformStoreGroups)) {
                platformStoreGroups.forEach(vo -> {
                    if (StringUtils.isNotEmpty(vo.getStoreIds())) {
                        String[] split = vo.getStoreIds().split(",");
                        List<String> addList = new ArrayList<>(split.length);
                        Collections.addAll(addList, split);
                        list.addAll(addList);
                    }

                });
            }
            list.add(String.valueOf(SecurityUtils.getStoreId()));
            queryWrapperStore.in("STORE_UID", list);
        } else if(ObjectUtil.isNotEmpty(SecurityUtils.getStoreId())){
            queryWrapperStore.eq("STORE_UID", SecurityUtils.getStoreId());
        }
        queryWrapperStore.in("SERVICE_TYPE", typeList);
        return platformStoreMapper.selectList(queryWrapperStore);
    }

}
